package com.kaka.starter.token.annotations.aop;

import com.kaka.starter.token.dto.TokenParamDTO;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by kaka on 2019/11/15
 */
@Aspect
@Component
@Order(1)
public class ConsoleTokenAspect {

    @Autowired
    private TokenParamDTO tokenParamDTO;

    @Around("@annotation(com.kaka.starter.token.annotations.ConsoleToken)")
    public Object doAccessCheck(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String authorization = request.getHeader(tokenParamDTO.getAuth());
        if (StringUtils.isBlank(authorization)) {
            throw new SignatureException("authorization is null");
        } else {
            return pjp.proceed();
        }

    }
}
